package com.example.xx.config;

import com.example.xx.util.JwtUtil;
import com.example.xx.util.LoginUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
 * 这是一个springsecurity自定义的一个过滤器
 * 用来验证token
 * @author xinxi
 * @date 2019/9/29 15:03
 * @description
 */
@Component
public class Jwtconfig extends OncePerRequestFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
       // 从请求头中获取jwt令牌
        String authorization = httpServletRequest.getHeader("Authorization");
        System.out.println("authorization:"+authorization);
        //判断请求头中是否有牌牌
        if(authorization==null){
            System.out.println("登录请求");
        }else {
            System.out.println("不是登录，是其他请求");
            // 如果带了  我们需要进一步验证是否是合法的
            //调用工具类  去解析jwt拿出用户名
            String userNameFromToken = jwtUtil.getUserNameFromToken(authorization);
            System.out.println("userNameFromToken:"+userNameFromToken);
            //判断redis有没有这个用户
            if(userNameFromToken!=null){
                //获取redis中的用户
                LoginUtil o = (LoginUtil) redisTemplate.opsForValue().get(userNameFromToken);
                //SimpleGrantedAuthority是GrantedAuthority的实现类 因为下面需要这个来封装 权限信息
                List<SimpleGrantedAuthority> sim=o.getQuanxian().stream().map(s->new SimpleGrantedAuthority(s)).collect(Collectors.toList());
                //第一个参数是用户名 第二个是密码 第三个是这个人的权限信息 是GrantedAuthority接口的实现类
                UsernamePasswordAuthenticationToken upa = new UsernamePasswordAuthenticationToken(userNameFromToken,o.getPwd(),sim);
                SecurityContextHolder.getContext().setAuthentication(upa);
            }else {
                System.out.println("redis中没有这个用户");
                System.out.println("解析失败");
            }

        }
        // 放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
